 function varargout = APEviewer(varargin)
% APEVIEWER MATLAB code for APEviewer.fig
%      APEVIEWER, by itself, creates a new APEVIEWER or raises the existing
%      singleton*.
%
%      H = APEVIEWER returns the handle to a new APEVIEWER or the handle to
%      the existing singleton*.
%
%      APEVIEWER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in APEVIEWER.M with the given input arguments.
%
%      APEVIEWER('Property','Value',...) creates a new APEVIEWER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before APEviewer_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to APEviewer_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help APEviewer

% Last Modified by GUIDE v2.5 14-Aug-2012 21:47:46

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @APEviewer_OpeningFcn, ...
                   'gui_OutputFcn',  @APEviewer_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before APEviewer is made visible.
function APEviewer_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to APEviewer (see VARARGIN)

% Choose default command line output for APEviewer
handles.output = hObject;
APEsplash(2);
% Generate Loadingindex:
handles.datasetsloaded(1:10)  = 0;

% Avoid LaTeX in Filenames:
set(gcf,'DefaultTextInterpreter','none')

% % Add SpectroLAB Logo
% rgb = imread('slspectrolab.jpg');
% axes(handles.logoAxes);
% image(rgb);
% set(handles.logoAxes,'xcolor',get(gcf,'color'));
% set(handles.logoAxes,'ycolor',get(gcf,'color'));
% set(handles.logoAxes,'ytick',[]);
% set(handles.logoAxes,'xtick',[]);

% initialize Lines for marking in plot
handles.line1 = line([],[],'Color','g',...
        'LineStyle','--'); % initialize line 1
handles.line2 = line([],[],'Color','r',...
        'LineStyle','--'); % initialize line 2

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes APEviewer wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = APEviewer_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


function listbox1_Callback(hObject, eventdata, handles)

listindex       = get(handles.listbox1, 'Value');
if handles.datasetsloaded(listindex) == listindex
    updatestatus(['Switching to ',num2str(listindex)],hObject)
    switchactivefile(hObject, eventdata, handles)
else
    updatestatus('not loaded yet',hObject)
end


function listbox1_CreateFcn(hObject, eventdata, handles)

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function addfilebutton_Callback(hObject, eventdata, handles)
listindex                   = get(handles.listbox1, 'Value');
% assignstring                = ['handles.datasets.',num2str(listindex)]
[FileName,PathName,~]       = uigetfile({'*.mat';'*.*'});

handles.FileName            = FileName;
handles.PathName            = PathName;
listoptions = get(handles.listbox1, 'String');
listoptions(listindex) = {['File ',num2str(listindex),' - ',FileName]};
set(handles.listbox1, 'String', listoptions)
handles.datasetsloaded(listindex)  = listindex;
handles.datasets(listindex).data = load(fullfile(PathName,FileName));

    updatestatus(['Loaded ',FileName], hObject)

% Update handles structure
guidata(hObject, handles);
switchactivefile(hObject, eventdata, handles)

function switchactivefile(hObject, eventdata, handles)

listindex=get(handles.listbox1, 'Value');
handles.dataset             = handles.datasets(listindex).data;
handles.dataset.plotx       = handles.dataset.datax;
handles.dataset.ploty       = handles.dataset.datay;
handles.dataset.xlabel      = 'datax';
handles.dataset.ylabel      = 'datay';
handles.dataset.title       = handles.dataset.footer.FileName;

% ----- check for MULTIPLE SPECTRA -----
if length(handles.dataset.datay(1,:))>1
    set(handles.multiBox,'Enable','on','Value',1)
else    
    set(handles.multiBox,'Enable','off','Value',0)
end
% ----- check for ALS DATA -----
if ~isfield(handles.dataset,'ALSdatay')
    set(handles.ydatapopup, 'Enable', 'off')
    set(handles.ALSBox,'Enable','off','Value',0)
else
    set(handles.ydatapopup, 'Enable', 'on')
    set(handles.ALSBox,'Enable','on','Value',1)
end
% ----- check for RAMAN DATA -----
if ~isfield(handles.dataset,'ramandatax')     
    set(handles.xdatapopup, 'Enable', 'off')
    set(handles.ramanBox,'Enable','off','Value',0)
else
    set(handles.xdatapopup, 'Enable', 'on')
    set(handles.ramanBox,'Enable','on','Value',1)
end
% ----- check for RAMAN Laser -----
if ~isfield(handles.dataset,'Laser_exwavelength') 
    set(handles.laserBox,'Enable','off','Value',0)
else
    set(handles.laserBox,'Enable','on','Value',1)
end
% ----- check for DOSE -----
if ~isfield(handles.dataset,'dose')
    set(handles.doseBox,'Enable','off','Value',0)
else
    set(handles.doseBox,'Enable','on','Value',1)
end
% ----- Enable GUI choices -----
    set(handles.axisSmallerBtn, 'Enable', 'on')
    set(handles.axisLargerBtn, 'Enable', 'on')
    set(handles.axisResetBtn, 'Enable', 'on')
    set(handles.axisCenterBtn, 'Enable', 'on')
    
%plot(handles.mainaxes, handles.datasets(1).datax, handles.datasets(1).datay)

% Update handles structure
guidata(hObject, handles);
replotmainaxes(hObject, eventdata, handles)


function removefilebutton_Callback(hObject, eventdata, handles)
listindex                   = get(handles.listbox1, 'Value');
% assignstring                = ['handles.datasets.',num2str(listindex)]

listoptions = get(handles.listbox1, 'String');

switch char(listoptions(listindex))
    case 'empty'
    otherwise
        listoptions(listindex) = {'empty'};    
        set(handles.listbox1, 'String', listoptions)
        handles.datasetsloaded(listindex)  = 0;
        clear handles.datasets(listindex).data
        cla(handles.mainaxes,'reset')
end
guidata(hObject, handles);


function clearbutton_Callback(hObject, eventdata, handles)

for listindex =1:9
        listoptions(listindex) = {'empty'};    
        handles.datasetsloaded(listindex)  = 0;
end
set(handles.listbox1, 'String', listoptions)
cla(handles.mainaxes,'reset')
cla(handles.supportaxes,'reset')
clear handles.datasets
clear handles.dataset       %for some reason does not work??
guidata(hObject, handles);



    


function xdatapopup_Callback(hObject, eventdata, handles)
val = get(handles.xdatapopup,'Value');
switch val
    case 2 % User selected raw datax
        handles.dataset.plotx = handles.dataset.datax;
        handles.dataset.xlabel = 'Wavelength (nm)';
        replotmainaxes(hObject, eventdata, handles);
    case 3 % User selected ramandatax
        handles.dataset.plotx = handles.dataset.ramandatax;
        handles.dataset.xlabel = 'Raman Shift (cm^-^1)';        
        replotmainaxes(hObject, eventdata, handles);
    case 1 % User selected wrong
        updatestatus('Zonk',hObject)
end
guidata(hObject, handles); % Save the handles structure after adding data


function xdatapopup_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function ydatapopup_Callback(hObject, eventdata, handles)

val = get(handles.ydatapopup,'Value');
switch val
    case 2 % User selected raw
        handles.dataset.ploty = handles.dataset.datay;
        handles.dataset.ylabel = 'A.U.';
        replotmainaxes(hObject, eventdata, handles);

    case 3 % User selected ALS
        handles.dataset.ploty       = handles.dataset.ALSdatay;
        handles.dataset.ylabel      = 'Raman Intensity';
        handles.supportdata.ploty   = handles.dataset.ALSbasey;
        handles.supportdata.plotx   = handles.dataset.plotx;
        handles.supportdata.ylabel  = 'Relative Base';
        handles.supportdata.xlabel  = handles.dataset.xlabel;
        replotmainaxes(hObject, eventdata, handles);
        replotsupportaxes(hObject, eventdata, handles);

    case 1 % User selected tooltip
        updatestatus('Zonk',hObject)
end
guidata(hObject, handles)


function ydatapopup_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function replotmainaxes(hObject, eventdata, handles)

% % -- DEBUG
% if exist('handles.dataset.ALSdatay')
%     updatestatus('ALSdatay is here',hObject)
% end
% % --
set(handles.overlayOnOff, 'Value', 0)

cla(handles.mainaxes)
cla(handles.supportaxes)

    plot(handles.mainaxes, handles.dataset.plotx, handles.dataset.ploty)
        Xlabel(handles.dataset.xlabel)
        Ylabel(handles.dataset.ylabel)
        title(handles.dataset.title)
        axis tight
    % reinitialize Lines for marking in plot
    handles.line1 = line([],[],'Color','g',...
        'LineStyle','--'); % initialize line 1
    handles.line2 = line([],[],'Color','r',...
        'LineStyle','--'); % initialize line 2

Xmax = max(handles.dataset.plotx);
Xmin = min(handles.dataset.plotx);
set(handles.lowerWLinput, 'String', num2str(Xmin))
set(handles.upperWLinput, 'String', num2str(Xmax))
guidata(hObject, handles)

        
        
        
function replotsupportaxes(hObject, eventdata, handles)

    plot(handles.supportaxes, handles.supportdata.plotx, ...
        handles.supportdata.ploty,'r')
        Xlabel(handles.supportdata.xlabel)
        Ylabel(handles.supportdata.ylabel)
        set(handles.supportaxes,'Xlim', get(handles.mainaxes,'XLim'));

        guidata(hObject, handles)
        

function exitbutton_Callback(hObject, eventdata, handles)
close all


function restartbutton_Callback(hObject, eventdata, handles)
closeGUI = handles.figure1; %handles.figure1 is the GUI figure

guiPosition = get(handles.figure1,'Position'); %get the position of the GUI
guiName = get(handles.figure1,'Name'); %get the name of the GUI

close(closeGUI); %close the old GUI
eval(guiName) %call the GUI again

set(gcf,'Position',guiPosition); %set the position for the new GUI


function reversex_Callback(hObject, eventdata, handles)
if get(handles.reversex, 'Value') ==1
    set(handles.mainaxes, 'Xdir', 'reverse')
    set(handles.supportaxes, 'Xdir', 'reverse')
elseif get(handles.reversex, 'Value') ==0
    set(handles.mainaxes, 'Xdir', 'normal')
    set(handles.supportaxes, 'Xdir', 'normal')
end

function reversey_Callback(hObject, eventdata, handles)
if get(handles.reversey, 'Value') ==1
    set(handles.mainaxes, 'Ydir', 'reverse')
    set(handles.supportaxes, 'Ydir', 'reverse')
elseif get(handles.reversey, 'Value') ==0
    set(handles.mainaxes, 'Ydir', 'normal')
    set(handles.supportaxes, 'Ydir', 'normal')
end

function logx_Callback(hObject, eventdata, handles)
if get(handles.logx, 'Value') ==1
    set(handles.mainaxes, 'Xscale', 'log')
    set(handles.supportaxes, 'Xscale', 'log')
elseif get(handles.logx, 'Value') ==0
    set(handles.mainaxes, 'Xscale', 'linear')
    set(handles.supportaxes, 'Xscale', 'linear')
end

function logy_Callback(hObject, eventdata, handles)
if get(handles.logy, 'Value') ==1
    set(handles.mainaxes, 'Yscale', 'log')
    set(handles.supportaxes, 'Yscale', 'log')
elseif get(handles.logy, 'Value') ==0
    set(handles.mainaxes, 'Yscale', 'linear')
    set(handles.supportaxes, 'Yscale', 'linear')
end


function updatestatus(message, hObject)
    handles = guidata(hObject);
    set(handles.statusbar, 'String', message)
    guidata(hObject, handles)


function overlaybutton_Callback(hObject, eventdata, handles)

handles.datasetsload = handles.datasetsloaded;
guidata(hObject, handles);
handles.overlayindex = 0;
handles.overlayindex = APEviewerPopup1('APEviewer',handles.figure1);
handles.datasetsloaded = handles.datasetsload;
set(handles.overlayOnOff, 'Enable', 'on');
overlayGraphs(hObject, eventdata, handles)

function overlayGraphs(hObject, eventdata, handles)
    cla(handles.mainaxes)
    cla(handles.supportaxes)

%     %% > DEBUG =======================================================================================
%     length(handles.overlayindex)
%     whos
%     handles
%     return
% %% ^ DEBUG =======================================================================================        

    set(handles.mainaxes, 'ColorOrder', [0 0 1; 0 0 1; 0.5 0 0.5; 1 0 0; 0.5 0.5 0; 0 1 0 ; 0 0.5 0.5; 0.5 0.5 0.5; 0.3 0.3 0.3; 0 0 0]);
    set(handles.supportaxes, 'ColorOrder', [0 0 1; 0.5 0 0.5; 1 0 0; 0.5 0.5 0; 0 1 0 ; 0 0.5 0.5; 0.5 0.5 0.5; 0.3 0.3 0.3; 0 0 0]);
    valy = get(handles.ydatapopup,'Value');
    valx = get(handles.xdatapopup,'Value');

    j=1;
    for i=1:9
        if handles.overlayindex(i) == 1

            switch valy
                case 3 % User selected ALS
                    ploty       = handles.datasets(i).data.ALSdatay;
                    supporty    = handles.datasets(i).data.ALSbasey;
                otherwise  % User selected raw
                    ploty = handles.datasets(i).data.datay;
            end
            switch valx                
                case 3 % User selected raman calibration
                    plotx = handles.datasets(i).data.ramandatax;
                otherwise % User selected raw
                    plotx = handles.datasets(i).data.datax;
            end 
            axes(handles.mainaxes)
                hold all
                plot(handles.mainaxes, plotx, ploty, ...
                    'DisplayName',['Plot ',num2str(i)])
                hold off
                totalMinMax(j,:) = [min(ploty) max(ploty)];

            if valy == 3
                axes(handles.supportaxes)
                    hold all
                    plot(handles.supportaxes, plotx, supporty, ...
                        'DisplayName',['Baseline ',num2str(i)])
                    hold off
                    totalsupportMinMax(j,:) = [min(supporty) max(supporty)];
            end
            j=j+1;
        end
    end
    legend('show')
    axes(handles.mainaxes)
    legend('show')
    hold off
    set(handles.mainaxes, 'Ylim', [min(totalMinMax(:,1)) max(totalMinMax(:,2))])
    if valy == 3
        set(handles.supportaxes, 'Ylim', ...
            [min(totalsupportMinMax(:,1)) max(totalsupportMinMax(:,2))])
    end
    set(handles.overlayOnOff, 'Value', 1)
guidata(hObject, handles);

function overlayOnOff_Callback(hObject, eventdata, handles)

if length(handles.overlayindex) > 1
        set(handles.overlayOnOff, 'Enable', 'on')
    val = get(handles.overlayOnOff, 'Value');
    switch val
        case 1
            overlayGraphs(hObject, eventdata, handles)
        otherwise
            legend('off')
            cla(handles.mainaxes)
            replotmainaxes(hObject, eventdata, handles)
    end
else
    set(handles.overlayOnOff, 'Enable', 'off')
end
                
        

        


%% ==========================  CONTEXT MENUS ==============================

function mainaxes_context_Callback(hObject, eventdata, handles)

function printAxes_Callback(hObject, eventdata, handles)
    print -noui

function printPreviewAxes_Callback(hObject, eventdata, handles)
    printpreview 

function plot_ax1_Callback(hObject, eventdata, handles)
% Displays contents of mainaxes at larger size in a new figure

% Create a figure to receive this axes' data
axes1fig = figure;
% Copy the axes and size it to the figure
axes1copy = copyobj(handles.mainaxes,axes1fig);
set(axes1copy,'Units','Normalized',...
              'Position',[.1,.1,.85,.75],...
              'Fontsize',8)
legend(axes1copy,'show')          
% Assemble a title for this new figure
newTitle = {'APEviewer Popout',get(get(axes1copy, 'Title'),'String')};
set(get(axes1copy, 'Title'),'Fontsize',12, ...
    'String',newTitle,...
    'Fontweight','bold')
set(get(axes1copy, 'Xlabel'),'Fontsize',10)
set(get(axes1copy, 'Ylabel'),'Fontsize',10)

% Save handles to new fig and axes in case
% we want to do anything else to them
handles.popoutaxes = axes1copy;
guidata(hObject,handles);

%% ===========================  CALL BACKS ================================

function axisSlider_Callback(hObject, eventdata, handles)
sliderValue = get(handles.axisSlider,'Value');

Yscale      = get(handles.mainaxes, 'Ylim');
Ymax        = max(handles.dataset.ploty);
Ymin        = min(handles.dataset.ploty);
Yrange      = Yscale(2)-Yscale(1);

newYminmin  = Ymin-Yrange;
newYminmax  = Ymax;
newYrange   = newYminmax-newYminmin; 
newYmin     = newYminmin+(sliderValue*newYrange);
newYscale   = [newYmin newYmin+Yrange];

set(handles.mainaxes, 'Ylim', [newYscale]);
guidata(hObject,handles);


function axisSlider_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function axisSmallerBtn_Callback(hObject, eventdata, handles)

Yscale = get(handles.mainaxes, 'Ylim');
Ymax = max(handles.dataset.ploty);
Ymin = min(handles.dataset.ploty);
tenStepSize = round((Ymax - Ymin)/10);
set(handles.mainaxes, 'Ylim', [Yscale(1)-(tenStepSize/2) Yscale(2)+(tenStepSize/2)])

if Yscale(1)-(tenStepSize/2) == Ymin
    set(handles.axisSlider, 'Enable', 'off')
else
    set(handles.axisSlider, 'Enable', 'on')
end
guidata(hObject,handles);


function axisLargerBtn_Callback(hObject, eventdata, handles)
Yscale = get(handles.mainaxes, 'Ylim');
Ymax = max(handles.dataset.ploty);
Ymin = min(handles.dataset.ploty);
tenStepSize = round((Ymax - Ymin)/10);

newYmin = Yscale(1)+(tenStepSize/2);
newYmax = Yscale(2)-(tenStepSize/2);
if newYmin < newYmax
    set(handles.mainaxes, 'Ylim', [newYmin newYmax])
end
if newYmin == Ymin
    set(handles.axisSlider, 'Enable', 'off')
else
    set(handles.axisSlider, 'Enable', 'on')
end
guidata(hObject,handles);

function axisResetBtn_Callback(hObject, eventdata, handles)
Ymax = max(handles.dataset.ploty);
Ymin = min(handles.dataset.ploty);
set(handles.mainaxes, 'Ylim', [Ymin Ymax])
set(handles.axisSlider, 'Enable', 'off', 'Value', 0.5)


Xmax = max(handles.dataset.plotx);
Xmin = min(handles.dataset.plotx);
set(handles.mainaxes, 'Xlim', [Xmin Xmax])
set(handles.lowerWLinput, 'String', num2str(Xmin))
set(handles.upperWLinput, 'String', num2str(Xmax))


function axisCenterBtn_Callback(hObject, eventdata, handles)
set(handles.axisSlider, 'Value', 0.5)
axisSlider_Callback(hObject, eventdata, handles)


function enableDataCursor_Callback(hObject, eventdata, handles)



function dataCursorBtn_Callback(hObject, eventdata, handles)
datacursormode toggle

function multiBox_Callback(hObject, eventdata, handles)
numberOfSpectra = length(handles.dataset.datay(1,:));
helptext = {['There are ',num2str(numberOfSpectra),' spectra']; ...
            'inside this dataset.'};
infobox = helpdlg(helptext,'Number of Spectra');
set(handles.multiBox,'Enable','on','Value',1)


function doseBox_Callback(hObject, eventdata, handles)
helptext = {'Following dose information is stored'; ...
            'inside this dataset:';'';...
            [num2str(handles.dataset.dose)]};
infobox = helpdlg(helptext,'Dose Information');
set(handles.doseBox,'Enable','on','Value',1)

function laserBox_Callback(hObject, eventdata, handles)
helptext = {'Wavelength of Raman Exitation Laser'; ...
            ['was set to ', num2str(handles.dataset.Laser_exwavelength),' nm.']};
infobox = helpdlg(helptext,'Laser Wavelength');
set(handles.laserBox,'Enable','on','Value',1)

function ALSBox_Callback(hObject, eventdata, handles)
helptext = {'The parameters for ALS correction'; ...
            'inside this dataset where:';'';...
            ['\lambda: ',(num2str(handles.dataset.ALSpara{1,2}))];...
            ['p: ',(num2str(handles.dataset.ALSpara{2,2}))];...
            ['Itterations: ',(num2str(handles.dataset.ALSpara{3,2}))]};
infobox = helpdlg(helptext,'ALS Iformation');
set(handles.doseBox,'Enable','on','Value',1)


function lowerWLinput_Callback(hObject, eventdata, handles)
% sets the lower limit for the Xaxis via input field in GUI
xlimits = get(handles.mainaxes, 'Xlim');
xmin = str2num(get(handles.lowerWLinput, 'String'));

if xmin>xlimits(2)
    warning('Lower Xlimit is higher than upper Xlimit')
    updatestatus('Higher Xlimit is smaller than lower Xlimit',hObject)
else
    xlimits(1)=xmin;
    set(handles.mainaxes, 'Xlim', xlimits);
    set(handles.supportaxes, 'Xlim', xlimits);
end


function lowerWLinput_CreateFcn(hObject, eventdata, handles)

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function upperWLinput_Callback(hObject, eventdata, handles)
% sets the upper limit for the Xaxis via input field in GUI
xlimits = get(handles.mainaxes, 'Xlim');
xmax = str2num(get(handles.upperWLinput, 'String'));

if xmax<xlimits(1)
    warning('Higher Xlimit is smaller than lower Xlimit!')
    updatestatus('Higher Xlimit is smaller than lower Xlimit!',hObject)
else
    xlimits(2)= xmax;
    set(handles.mainaxes, 'Xlim', xlimits);
    set(handles.supportaxes, 'Xlim', xlimits);
end


function upperWLinput_CreateFcn(hObject, eventdata, handles)

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


       


function line1checkbox_Callback(hObject, eventdata, handles)

if get(handles.line1checkbox, 'Value') == 0
    line1obj = findobj('Color','g',...
        'LineStyle','--');
    set(line1obj, 'XData', [], 'YData', []);
else
    drawline1(hObject, eventdata, handles)
end

function line1input_Callback(hObject, eventdata, handles)

if get(handles.line1checkbox, 'Value') == 0
    set(handles.line1checkbox, 'Value',1)
end
drawline1(hObject, eventdata, handles);


function line1input_CreateFcn(hObject, eventdata, handles)

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function line2input_Callback(hObject, eventdata, handles)

if get(handles.line2checkbox, 'Value') == 0
    set(handles.line2checkbox, 'Value',1)
end
drawline2(hObject, eventdata, handles);

    
function line2checkbox_Callback(hObject, eventdata, handles)

if get(handles.line2checkbox, 'Value') == 0
    line2obj = findobj('Color','r',...
        'LineStyle','--');
    set(line2obj, 'XData', [], 'YData', []);
else
    drawline2(hObject, eventdata, handles)
end


function drawline1(hObject, eventdata, handles)
% Draws a red line in the main and support axes

if isempty(get(handles.line1input, 'String'))
    xlimit = get(handles.mainaxes, 'Xlim');
    xmid = ((xlimit(2)-xlimit(1))/2)+xlimit(1);
    xlimit = [xmid xmid];
    set(handles.line1input, 'String', num2str(xmid))
else
    xpos = str2num(get(handles.line1input, 'String'));
    xlimit = [xpos xpos];
end
ylimit = get(handles.mainaxes, 'Ylim');

line1obj = findobj('Color','g',...
        'LineStyle','--');
    set(line1obj, 'XData', [], 'YData', []);
handles.line1 = line(xlimit,[0 ylimit(2)],'Color','g',...
        'LineStyle','--');
    
guidata(hObject,handles);

function drawline2(hObject, eventdata, handles)
% Draws a red line in the main and support axes

if isempty(get(handles.line2input, 'String'))
    xlimit = get(handles.mainaxes, 'Xlim');
    xmid = ((xlimit(2)-xlimit(1))/2)+xlimit(1);
    xlimit = [xmid xmid];
    set(handles.line2input, 'String', num2str(xmid))
else
    xpos = str2num(get(handles.line2input, 'String'));
    xlimit = [xpos xpos];
end
ylimit = get(handles.mainaxes, 'Ylim');
line2obj = findobj('Color','r',...
        'LineStyle','--');
    set(line2obj, 'XData', [], 'YData', []);
handles.line2 = line(xlimit,[0 ylimit(2)],'Color','r',...
        'LineStyle','--');
    
guidata(hObject,handles);



function line2input_CreateFcn(hObject, eventdata, handles)

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
